<?php

namespace app\supplier\controller;

use app\erp\model\Dianzidb;
use app\erp\model\OrderApplyEinvoicedb;
use app\erp\model\Orderdb;
use app\erp\model\Expressdb;
use app\erp\model\Cartdb;
use app\erp\model\Installdb;
use app\erp\model\OrderGoodsRemarkdb;
use app\erp\model\OrderRemarkdb;
use app\erp\model\Returneddb;
use app\erp\model\Runsdb;
use app\erp\model\Shoppingdb;
use app\erp\model\Postwuliudb;
use app\erp\model\Sitedb;
use app\api\controller\Neimeng;
use app\api\controller\Henan;
use app\api\controller\Qixin;
use app\erp\model\Memberdb;
use app\erp\model\Goodsdb;
use app\erp\model\OrderLogdb;
use app\erp\model\Branddb;
use app\erp\model\UCartdb;
use app\erp\model\UOrderdb;
use app\erp\model\UOrderGoodsRemarkdb;
use think\Db;
use app\erp\model\Buildtpldb;
use app\erp\model\SiteConfigdb;

class Order extends Base
{
    protected $db;
    protected $cols = array(
        array(
            'field' => 'order_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox'
        ),
        array(
            'field' => 'create_time',
            'width' => 120,
            'title' => '下单时间'
        ),
        array(
            'field' => 'citys',
            'width' => 200,
            'title' => '省市'
        ),
        array(
            'field' => 'address',
            'width' => 200,
            'title' => '地址'
        ),
        array(
            'field' => 'push_supplier_time',
            'width' => 150,
            'title' => '指派时间'
        ),
        array(
            'field' => 'order_money',
            'width' => 120,
            'title' => '订单金额',
            'totalRow' => true
        ),
        array(
            'field' => 'supplier_rate_money',
            'width' => 120,
            'title' => '折扣金额',
            'totalRow' => true
        ),
        array(
            'field' => 'order_type',
            'width' => 120,
            'title' => '订单类型',
            'templet' => '#order_typeTpl'
        ),
        array(
            'field' => 'remark',
            'width' => 120,
            'title' => '客服提醒'
        ),
        array(
            'field' => 'out_order_no',
            'width' => 190,
            'title' => '军网订单号',
            'templet' => '#out_order_noTpl'
        ),
        array(
            'field' => 'gys_sh_time',
            'width' => 150,
            'title' => '收货时间',
        ),
        array(
            'field' => 'supplier_state',
            'width' => 90,
            'title' => '确认状态',
            'templet' => '#supplier_stateTpl'
        ),
        array(
            'field' => 'gys_fh_state',
            'width' => 60,
            'title' => '发货',
            'templet' => '#gys_fh_stateTpl'
        ),
        array(
            'field' => 'gys_sh_state',
            'width' => 60,
            'title' => '收货',
            'templet' => '#gys_sh_stateTpl'
        ),
        array(
            'field' => 'apply_state',
            'width' => 90,
            'title' => '发票申请',
            'templet' => '#apply_stateTpl'
        ),
        array(
            'field' => 'returncode',
            'width' => 90,
            'title' => '电子发票',
            'templet' => '#returncodeTpl'
        ),
        array(
            'field' => 'invoice_proof',
            'width' => 60,
            'title' => '发票',
            'templet' => '#invoice_stateTpl'
        ),
        array(
            'field' => 'caigou_invoice_duty',
            'width' => 90,
            'title' => '采购发票',
            'templet' => '#caigou_invoice_dutyTpl'
        ),
        array(
            'field' => 'pay_state',
            'width' => 60,
            'title' => '收款',
            'templet' => '#pay_stateTpl'
        ),
        array(
            'field' => 'caigou_hetong',
            'width' => 90,
            'title' => '采购合同',
            'templet' => '#caigou_hetongTpl'
        ),
        array(
            'field' => 'ghs_pay',
            'width' => 60,
            'title' => '付款',
            'templet' => '#ghs_payTpl'
        ),
        array(
            'field' => 'jun_order_state',
            'width' => 90,
            'title' => '推送状态',
            'templet' => '#jun_order_stateTpl'
        ),
        array(
            'field' => 'contacts',
            'width' => 120,
            'title' => '收货人'
        ),
        array(
            'field' => 'contacts_phone',
            'width' => 120,
            'title' => '收货人电话'
        ),
        array(
            'field' => 'suppler_bz',
            'width' => 120,
            'title' => '备注'
        ),
        array(
            'width' => 50,
            'toolbar' => '#order_tool',
            'title' => '',
            'fixed' => 'right'
        )
    );
    protected $order_goods_cols = array(
        array(
            'field' => 'goods_id',
            'width' => 40,
            'hide' => true
        ),
        array(
            'field'=>'jun_id',
            'width'=>120,
            'title'=>'军网编号'
        ),
        array(
            'field' => 'goods_name',
            'width' => 360,
            'title' => '商品名称'
        ),
        array(
            'field' => 'goods_sale_price',
            'width' => 120,
            'title' => '价格'
        ),
        array(
            'field' => 'goods_num',
            'width' => 60,
            'title' => '数量'
        ),
        array(
            'field' => 'all_sale_price',
            'width' => 120,
            'title' => '总金额'
        ),
        array(
            'field' => 'diy_gys',
            'width' => 228,
            'title' => '供应商',
            'edit' => true
        ),
        array(
            'field' => 'div_cgj',
            'width' => 120,
            'title' => '采购价',
            'edit' => true
        ),
        array(
            'field' => 'diy_fpzt',
            'width' => 120,
            'title' => '发票状态',
            'edit' => true

        ),
        array(
            'field' => 'diy_fpdj',
            'width' => 170,
            'title' => '发票登记',
            'edit' => true
        ),
        array(
            'field' => 'goods_sku',
            'width' => 200,
            'title' => '产品编码'
        ),
        array(
            'field' => 'goods_jun_id',
            'width' => 130,
            'title' => '军网编码'
        )
    );
    protected $member_cols = array(
        array(
            'field' => 'member_id',
            'width' => 40,
            'title' => '编号',
            'type' => 'radio'
        ),
        array(
            'field' => 'username',
            'width' => 160,
            'title' => '登录名',
            'sort' => 'true'
        ),
        array(
            'field' => 'realname',
            'width' => 160,
            'title' => '姓名',
            'sort' => 'true'
        ),
        array(
            'field' => 'phone',
            'width' => 160,
            'title' => '联系电话',
            'sort' => 'true'
        ),
        array(
            'field' => 'email',
            'width' => 220,
            'title' => '邮箱',
            'sort' => 'true'
        )
    );
    protected $goods_cols = array(
        array(
            'field' => 'category_name',
            'title' => '分类'
        ),
        array(
            'field' => 'brand_name',
            'title' => '品牌'
        ),
        array(
            'field' => 'goods_picture',
            'title' => '封面',
            'width' => 60,
            'templet' => '#goods_pictureTpl'
        ),
        array(
            'field' => 'goods_sku',
            'title' => '商品编号'
        ),
        array(
            'field' => 'goods_name',
            'title' => '商品名称'
        ),
        array(
            'field' => 'sale_attr',
            'title' => '属性',
            'templet' => '#sale_attrTpl'
        ),
        array(
            'field' => 'sale_price',
            'width' => 100,
            'title' => '价格',
            'edit' => true,
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'num',
            'title' => '数量',
            'width' => 80,
            'edit' => true,
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'width' => 100,
            'toolbar' => '#goods_tool',
            'title' => '操作',
            'fixed' => 'right'
        )
    );
    protected $goods_cols_state2 = array(
        array(
            'width' => 40,
            'field' => 'goods_id',
            'title' => '编号',
            'type' => 'checkbox',
            'hide' => true
        ),
        array(
            'width' => 190,
            'field' => 'goods_name',
            'title' => '商品名称'
        ),
        array(
            'width' => 120,
            'field' => 'jun_id',
            'title' => '军网编码'
        ),
        array(
            'field' => 'sale_price',
            'width' => 80,
            'title' => '价格',
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'num',
            'title' => '数量',
            'width' => 60,
            'style' => 'text-align:center;font-size:16px;color:#ff6600',
            'templet' => '#cart_numTpl'
        ),
        array(
            'field' => 'buhanshui',
            'width' => 110,
            'title' => '不含税金额',
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'shuie',
            'width' => 110,
            'title' => '税额',
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'category_name',
            'width' => 90,
            'title' => '分类'
        ),

        array(
            'field' => 'cart_goods_beizhu',
            'width' => 110,
            'title' => '备注',
            'edit' => true
        ),

        array(
            'field' => 'goods_sku',
            'width' => 150,
            'title' => '商品编号'
        ),

        array(
            'width' => 180,
            'field' => 'shuiwu_id',
            'title' => '税务编码'
        ),
        array(
            'width' => 230,
            'field' => 'product_area',
            'title' => '税务大类'
        ),
        array(
            'width' => 130,
            'field' => 'product_firm',
            'title' => '开票名称'
        ),
        array(
            'width' => 300,
            'field' => 'goods_model',
            'title' => '规格型号(若不要型号，只需输一个空格)'
        ),
        array(
            'width' => 60,
            'field' => 'goods_keywords',
            'title' => '税率'
        ),

        array(
            'width' => 120,
            'toolbar' => '#goods_tool',
            'title' => '操作',

        )
    );
    protected $goods_cols_invoice = array(
        array(
            'field' => 'goods_sku',
            'title' => '商品编号',
            'hide' => true
        ),
        array(
            'width' => 250,
            'field' => 'product_area',
            'title' => '税务大类 <strong>(改大类必须改编码)</strong>',
            'edit' => true
        ),
        array(
            'width' => 180,
            'field' => 'shuiwu_id',
            'title' => '税务编码',
            'edit' => true
        ),
        array(
            'width' => 130,
            'field' => 'product_firm',
            'title' => '开票名称',
            'edit' => true
        ),
        array(
            'width' => 260,
            'field' => 'invoice_model',
            'title' => '规格型号',
            'edit' => true
        ),
        array(
            'width' => 60,
            'field' => 'goods_unit',
            'title' => '单位',
            'edit' => true
        ),
        array(
            'width' => 90,
            'field' => 'sale_price',
            'title' => '单价'
        ),

        array(
            'width' => 60,
            'field' => 'goods_keywords',
            'title' => '税率'
        ),
        array(
            'width' => 120,
            'field' => 'all_sale_price',
            'title' => '总金额'
        ),
        array(
            'width' => 120,
            'field' => 'diy_beizhu',
            'title' => '订单备注',
            'hide' => true
        )
    );
    protected $select_goods_cols = array(
        array(
            'field' => 'goods_id',
            'width' => 40,
            'type' => 'radio',
            'title' => '选择'
        ),
        array(
            'field' => 'category_name',
            'width' => 100,
            'title' => '分类'
        ),
        array(
            'field' => 'brand_name',
            'width' => 100,
            'title' => '品牌'
        ),
        array(
            'field' => 'goods_picture',
            'title' => '封面',
            'width' => 60,
            'templet' => '#goods_pictureTpl'
        ),
        array(
            'field' => 'goods_sku',
            'width' => 120,
            'title' => '商品编号'
        ),
        array(
            'field' => 'goods_name',
            'width' => 300,
            'title' => '商品名称'
        ),
        array(
            'field' => 'sale_price',
            'width' => 100,
            'title' => '售价'
        ),
        array(
            'field' => 'market_price',
            'width' => 100,
            'title' => '市场价'
        )
    );
    public $post = array();
    private $host = '';

    public function _initialize()
    {
        ini_set('memory_limit', '256M');
        parent::_initialize();
        $request = request();
        $param = $request->param();
        $this->post = $param;
        $this->db = new Orderdb ();
        $this->db->param = $this->post;
    }

    public function getNeimengOrder()
    {
        $neimengapi = new Neimeng ();
        $return = $neimengapi->getOrderList();
    }

    public function getQixinOrder()
    {
        $qixinapi = new Qixin ();
        $return = $qixinapi->getOrderList();
    }

    public function pushHenan($order_no, $model = '')
    {
        $this->db->param ['order_no'];
        $get_order = $this->db->ajaxFind();
        $henanApi = new Henan ();
        if (isset ($model) && $model != '') {
            if ($model == 'contractDetail') {
                // 合同
                $henanApi->getContract($get_order ['out_order_no']);
            }
            if ($model == 'getOrderCheck') {
                // 验收状态
                $henanApi->getOrderCheck($get_order ['out_order_no']);
            }
            if ($model == 'payInfo') {
                // 确认支付
                $henanApi->orderPay($get_order);
            }
            if ($model == 'viewOrder') {
                // 查看订单
                $henanApi->getOrderInfo($get_order ['out_order_no']);
            }
            if ($model == 'sendInvoice') {
                // 开票
                $henanApi->sendInvoice($get_order ['out_order_no']);
            }
            if ($model == 'sendExpress') {
                // 发送唯一标识
                $post_data ['logisticsList'] = array(); // 发货时信息
                $expressdb = new Expressdb ();
                $expressdb->param ['order_no'] = $order_no;
                $get_express = $expressdb->ajaxList();
                $henanApi->sendOrderPic($get_order, $get_express);
            }
            if ($model == 'getInvoice') {
                $henanApi->signInvoice($get_order ['out_order_no']);
            }
            exit ();
        }
        if ($get_order ['order_state'] == 2) {
            // 确认订单
            $henanApi->confirmOrder($get_order ['out_order_no']);
        }
        if ($get_order ['order_state'] == 3) {
            $post_data ['logisticsList'] = array(); // 发货时信息
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $order_no;
            $get_express = $expressdb->ajaxList();
            // 发货
            $henanApi->express($get_express, $get_order ['out_order_no']);
        }
        if ($get_order ['order_state'] == 4) {
            // 订单收货
            $post_data ['logisticsList'] = array(); // 发货时信息
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $order_no;
            $get_express = $expressdb->ajaxList();
            $henanApi->signOrder($get_express, $get_order ['out_order_no']);
            //
        }
        if ($get_order ['order_state'] == -1) {
            // 取消订单
            $henanApi->channelOrder($get_order ['out_order_no']);
        }
        exit ();
    }

    public function pushNeimeng($order_no, $model = '')
    {
        $this->db->param ['order_no'];
        $get_order = $this->db->ajaxFind();
        $neimengapi = new Neimeng ();
        if (isset ($model) && $model != '') {
            if ($model == 'createContract') {
                $return = $neimengapi->createContract($get_order ['out_order_no']);
                if ($return ['code'] == 200) {
                    $this->db->param ['order_id'] = $get_order ['order_id'];
                    $this->db->param ['data'] = array(
                        'contract_no' => $return ['data']
                    );
                    $this->db->ajaxSaveOne();
                }
                echo '创建合同：' . $return ['message'];
            }
            if ($model == 'contractDetail') {
                $neimengapi->contractDetail($get_order ['contract_no']);
                // echo '获取合同：'.$return['message'];
            }
            if ($model == 'sendContract') {
                $neimengapi->sendContract($get_order ['contract_no']);
                // echo '发送合同：'.$return['message'];
            }
            exit ();
        }
        if ($get_order ['order_state'] == -1) {
            $return = $neimengapi->channelOrder($get_order ['out_order_no']);
            echo '订单取消状态：' . $return ['message'];
        } elseif ($get_order ['order_state'] == 4) {
            // 创建结算单
            $return = $neimengapi->createSettlement($get_order);
            echo '创建结算单：' . $return ['message'];
        } else {
            $return = $neimengapi->setOrder($order_no);
            echo '订单状态信息推送:' . $return ['message'];
            if ($return ['code'] != 200) {
                $this->db->param ['order_no'] = $order_no;
                $this->db->param ['data'] ['order_state'] = 2;
                // $this->db->saveStateBack();
            }
        }
    }

    public function pushQixin($order_no, $model = '')
    {
        $this->db->param ['order_no'];
        $get_order = $this->db->ajaxFind();
        $qixinapi = new Qixin ();
        if (isset ($model) && $model != '') {
            if ($model == 'createContract') {
                $return = $qixinapi->createContract($get_order ['out_order_no']);
                if ($return ['code'] == 200) {
                    $this->db->param ['order_id'] = $get_order ['order_id'];
                    $this->db->param ['data'] = array(
                        'contract_no' => $return ['data']
                    );
                    $this->db->ajaxSaveOne();
                }
                echo '创建合同：' . $return ['message'];
            }
            if ($model == 'contractDetail') {
                $qixinapi->contractDetail($get_order ['contract_no']);
                // echo '获取合同：'.$return['message'];
            }
            if ($model == 'sendContract') {
                $qixinapi->sendContract($get_order ['contract_no']);
                // echo '发送合同：'.$return['message'];
            }
            exit ();
        }
        if ($get_order ['order_state'] == -1) {
            $return = $qixinapi->channelOrder($get_order ['out_order_no']);
            echo '订单取消状态：' . $return ['message'];
        } elseif ($get_order ['order_state'] == 4) {
            // 创建结算单
            $return = $qixinapi->createSettlement($get_order);
            echo '创建结算单：' . $return ['message'];
        } else {
            $return = $qixinapi->setOrder($order_no);
            echo '订单状态信息推送:' . $return ['message'];
            if ($return ['code'] != 200) {
                $this->db->param ['order_no'] = $order_no;
                $this->db->param ['data'] ['order_state'] = 2;
                // $this->db->saveStateBack();
            }
        }
    }

    public function index()
    {
        // 获取分站信息
        $sitedb = new Sitedb ();
        $get_site = $sitedb->ajaxFind(SITE_ID);
        $this->assign('get_site', $get_site);
        $this->assign('cols', json_encode($this->cols));
        // 获取分站列表
        $sitedb->param ['_o'] = 'site_id';
        $sitedb->param ['_b'] = 'asc';
        $sitedb->param ['page'] = 1;
        $sitedb->param ['limit'] = 1000;
        $get_site_list = $sitedb->ajaxSelect();
        $this->assign('site_list', $get_site_list ['data']);
        $this->assign('order_goods_cols', json_encode($this->order_goods_cols));
        return $this->fetch();
    }

    public function saveApplyInfo()
    {
        $cartdb = new Cartdb();
        $data = $this->post['save_data'];
        $is_change = 0;
        Db::startTrans();
        foreach ($data as $key => $val) {
            $val['shuiwu_id'] = trim($val['shuiwu_id']);
            $val['product_area'] = trim($val['product_area']);
            $val['product_firm'] = trim($val['product_firm']);
            $val['goods_unit'] = trim($val['goods_unit']);
            $val['goods_keywords'] = trim($val['goods_keywords']);
            $get_cart = $cartdb->with(['goods'])->find($val['cart_id']);
            $save_update['product_area'] = $val['product_area'] ?: $get_cart['goods']['product_area'];
            $save_update['shuiwu_id'] = $val['shuiwu_id'] ?: $get_cart['goods']['shuiwu_id'];
            $save_update['product_firm'] = $val['product_firm'] ?: $get_cart['goods']['product_firm'];
            //$save_update['invoice_model'] = $val['invoice_model'] ?: $get_cart['goods']['invoice_model'];
            $save_update['invoice_model'] = $val['invoice_model'] ?: '　';
            $save_update['goods_unit'] = $val['goods_unit'] ?: $get_cart['goods']['goods_unit'];
            $save_update['goods_keywords'] = $val['goods_keywords'] ?: $get_cart['goods']['goods_keywords'];
            $save_update['apply_state'] = 2;
            $save_update['nopass_info'] = '';
            // $save_update['diy_beizhu'] = $val['diy_beizhu'];
            // 验证不能为空的数据
            if (strlen($save_update['shuiwu_id']) !== 19) {
                Db::rollback();
                $this->layuiReturn('税务编码需为19位数', 0, 'error', -1);
            }
            if ($save_update['product_area'] == '' && $get_cart['goods']['product_area'] == '') {
                Db::rollback();
                $this->layuiReturn('数据不能为空', 0, 'error', -1);
            }
            if ($save_update['shuiwu_id'] == '' && $get_cart['goods']['shuiwu_id'] == '') {
                Db::rollback();
                $this->layuiReturn('数据不能为空', 0, 'error', -1);
            }
            if ($save_update['product_firm'] == '' && $get_cart['goods']['product_firm'] == '') {
                Db::rollback();
                $this->layuiReturn('数据不能为空', 0, 'error', -1);
            }
            if ($save_update['goods_unit'] == '' && $get_cart['goods']['goods_unit'] == '') {
                Db::rollback();
                $this->layuiReturn('数据不能为空', 0, 'error', -1);
            }
            if ($save_update['goods_keywords'] == '' && $get_cart['goods']['goods_keywords'] == '') {
                Db::rollback();
                $this->layuiReturn('数据不能为空', 0, 'error', -1);
            }
            // 验证结束

            if ($val['product_area'] && $get_cart['product_area'] != $val['product_area']) {
                $is_change = 1;
            }
            if ($val['shuiwu_id'] && $get_cart['shuiwu_id'] != $val['shuiwu_id']) {
                $is_change = 1;
            }
            if ($val['product_firm'] && $get_cart['product_firm'] != $val['product_firm']) {
                $is_change = 1;
            }
            if ((!$get_cart['invoice_model'] && $get_cart['goods']['invoice_model'] != $save_update['invoice_model']) || ($get_cart['invoice_model'] && $get_cart['invoice_model'] != $save_update['invoice_model'])) {
                $is_change = 1;
            }
            if ($val['goods_unit'] && $get_cart['goods_unit'] != $val['goods_unit']) {
                $is_change = 1;
            }
            if ($val['goods_keywords'] && $get_cart['goods_keywords'] != $val['goods_keywords']) {
                $is_change = 1;
            }
            /*if ($val['diy_beizhu'] && $get_cart['diy_beizhu'] != $val['diy_beizhu']) {
                $is_change = 1;
            }*/
            $get_cart->save($save_update);
        }
        Db::commit();
        $save_apply['order_no'] = $this->post['order_no'];
        $save_apply['admin_id'] = MEMBER_ID;
        $save_apply['log'] = '申请电子发票';
        $orderApplyEinvoicedb = new OrderApplyEinvoicedb();
        $orderApplyEinvoicedb->save($save_apply);
        $get_order = $this->db->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            $get_order->save(['apply_state' => 2, 'apply_time' => time(), 'is_change' => $is_change]);
            /*$get_order->save(['apply_state' => 2]);
            $get_order->save(['apply_time' => time()]);*/
        }
        $this->layuiReturn('success');
    }

    // 撤销申请电子发票
    public function backApplyInfo()
    {
        $cartdb = new Cartdb();
        $data = $this->post['save_data'];
        foreach ($data as $key => $val) {
            $save_update['apply_state'] = 1;
            $save_update['product_area'] = '';
            $save_update['shuiwu_id'] = '';
            $save_update['product_firm'] = '';
            $save_update['invoice_model'] = '';
            $save_update['goods_unit'] = '';
            $save_update['goods_keywords'] = '';
            $save_update['nopass_info'] = '';
            $save_update['diy_beizhu'] = '';
            $cartdb->where('cart_id', $val['cart_id'])->update($save_update);
        }
        $save_apply['order_no'] = $this->post['order_no'];
        $save_apply['admin_id'] = MEMBER_ID;
        $save_apply['log'] = '撤销申请电子发票';
        $orderApplyEinvoicedb = new OrderApplyEinvoicedb();
        $orderApplyEinvoicedb->save($save_apply);
        $get_order = $this->db->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            $get_order->save(['apply_state' => 1, 'is_change' => 0]);
        }
        $this->layuiReturn('success');
    }

    public function saveCartInfo()
    {
        $cartdb = new Cartdb();
        $get_cart = $cartdb->find($this->post['cart_id']);
        $save_data[$this->post['field']] = $this->post['value'];
        $get_cart->save($save_data);
        $this->layuiReturn('success');
    }

    // 重新生成采购发票和销售发票
    public function resetfp()
    {
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            $get_order->save(['xsfp' => '生成中', 'cgfp' => '生成中']);
            //$orderdb->where('order_id', $get_order['order_id'])->update([$this->post['type'] => '生成中']);
            $save_data = [];
            $temp1 = [];
            $temp1['order_no'] = $get_order['order_no'];
            $temp1['buildtpl_type'] = 'xsfp';
            $temp1['state'] = 2;
            array_push($save_data, $temp1);
            $temp2 = [];
            $temp2['order_no'] = $get_order['order_no'];
            $temp2['buildtpl_type'] = 'cgfp';
            $temp2['state'] = 2;
            array_push($save_data, $temp2);
            $buildtpldb = new Buildtpldb();
            $buildtpldb->saveAll($save_data);
        }
        $this->layuiReturn('success');
    }

    /**
     *
     * @todo 列表
     */
    public function ajaxList()
    {
        unset ($this->db->param ['need_supplier']);
        $this->db->param ['rate_price'] = 'yes';
        $this->db->param ['supplier_id'] = MEMBER_ID;
        $return = $this->db->ajaxSelect();
        $this->layuiReturn($return ['data'], $return ['count']);
    }

    public function ajaxBaobeidan()
    {
        $chk = $this->db->where('out_order_no', $this->post['chk_out_order_no'])->find();
        if ($chk) {
            $chk = $chk->toArray();
            if (!$chk['supplier_id']) {
                $order_no = $chk['order_no'];
                $cartdb = new Cartdb();
                $cartdb->param['order_no'] = $order_no;
                $cartdb->param['need_goods_info'] = 'yes';
                $cartdb->param['no_more_price'] = 'yes';
                $get_cart = $cartdb->ajaxSelect();
                $this->layuiReturn($get_cart['data'], $get_cart['count']);
            } else {
                $this->layuiReturn('success', 0);
            }
        } else {
            $this->layuiReturn('success', 0);
        }

    }

    public function exportOrder()
    {
        set_time_limit(0);
        ini_set('memory_limit', -1);
        $this->db->param ['rate_price'] = 'yes';
        $this->db->param ['supplier_id'] = MEMBER_ID;
        $this->db->param ['need_goods_info'] = 'yes';
        $this->db->param['no_need_attr'] = 'yes';
        $this->db->param['no_need_goods_handle'] = 'yes';
        $this->db->param['no_need_returned'] = 'yes';
        $this->db->param['no_goods_picture'] = 'yes';
        $this->db->param['no_more_price'] = 'yes';
        $this->db->param['need_supplier'] = 'no';
        $this->db->param ['need_cart'] = 'yes';
        $count = $this->db->ajaxCount();
        $this->db->param ['page'] = 1;
        $this->db->param ['limit'] = $count;
        $data = $this->db->ajaxList();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '订单' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '订单号',
            '外部订单号',
            '订单时间',
            '订单金额',
            '采购金额',
            '收货地址',
            '收货人',
            '收货人电话',
            '订单状态',
            '指定供应商时间',
            '供应商确认时间',
            '支付状态',
            '发票状态',
            '发货状态',
            '发货时间',
            '收货状态',
            '收货日期',
            '客服提醒',
            '供应商备注1',
            '供应商备注2',
            '供应商备注3',
            '发票申请',
            '订单产品',
            '军网编号',
            '购买数量',
            '销售金额',
            '小计',
            '采购价',
            '供应商',
            '采购价',
            '发票状态',
            '发票登记'

        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_state_arr = array(
            '1' => '下单成功',
            '2' => '已确认订单',
            '3' => '订单已发货',
            '4' => '订单已收货',
            '5' => '订单已完成',
            '-1' => '订单已取消'
        );
        $pay_state_arr = array(
            '1' => '等待付款',
            '2' => '已付款',
            '3' => '部分付款'
        );
        $pay_type_arr = array(
            '1' => '货到付款',
            '2' => '在线支付',
            '3' => '账期支付',
            '4' => '银行转账'
        );
        $is_invoice_arr = array(
            '1' => '不开票',
            '2' => '独立开票',
            '3' => '统一开票'
        );
        $invoice_state_arr = array(
            '1' => '未开票',
            '2' => '已开票',
            '3' => '部分开票'
        );
        $gys_fh_state_arr = array(
            '1' => '已发货',
            '2' => '未发货'
        );
        $gys_sh_state_arr = array(
            '1' => '已收货',
            '2' => '未收货'
        );
        $caigou_invoice_duty_arr = array(
            '1' => '已开票',
            '2' => '未开票'
        );
        $shopping_state_arr = array(
            '1' => '未配送',
            '2' => '已配送',
            '3' => '部分配送'
        );
        $receipt_state_arr = array(
            '1' => '未收货',
            '2' => '已收货',
            '3' => '部分收货'
        );
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        $apply_state_arr = array(
            '' => '未提交',
            '1' => '未提交',
            '2' => '等待审核',
            '3' => '审核通过',
            '4' => '驳回'
        );
        foreach ($data as $key => $val) {
            foreach ($val ['cart_info'] as $k => $v) {
                unset ($temp);
                $supplier_rate = $val ['supplier_rate'] ? $val ['supplier_rate'] : 100;
                $temp [0] = $val ['order_no'];
                $temp [1] = $val ['out_order_no'];
                $temp [2] = $val ['create_time'];
                $temp [3] = $order_type_arr [$val ['order_type']];
                $temp [4] = $val ['order_money'];
                $temp [5] = number_format($val ['supplier_rate_money'], 2, '.', '');
                $temp [6] = $val ['shopping_info'] ['province_name'] . $val ['shopping_info'] ['city_name'] . $val ['shopping_info'] ['area_name'] . $val ['shopping_info'] ['street'];
                $temp [7] = $val ['contacts'];
                $temp [8] = $val ['contacts_phone'];
                $temp [9] = $order_state_arr [$val ['order_state']];
                $temp [10] = $val ['push_supplier_time'];
                $temp [11] = $val ['supplier_confirm_time'];
                /*$pay_type = $val ['pay_type'] ? $val ['pay_type'] : 1;
                if(isset($pay_type_arr[$pay_type])){
                    $temp[12] = $pay_state_arr [$pay_type];
                } else {
                    $temp[12] = $pay_state_arr [1];
                }*/
                $temp[12] = $invoice_state_arr[$val['invoice_state']];

                $temp [13] = $caigou_invoice_duty_arr [$val ['caigou_invoice_duty'] ? 1 : 2];
                $temp [14] = $gys_fh_state_arr [$val ['gys_fh_state']];
                $temp [15] = $val ['gys_fh_time'] ? (is_numeric($val ['gys_fh_time']) ? date('Y-m-d H:i:s', $val ['gys_fh_time']) : $val ['gys_fh_time']) : '';
                $temp [16] = $gys_sh_state_arr [$val ['gys_sh_state']];
                $temp [17] = $val ['gys_sh_time'] ?: '';
                $temp [18] = $val ['remark'];
                $temp [19] = $val ['suppler_bz'];
                $temp [20] = $val ['suppler_bz2'];
                $temp [21] = $val ['suppler_bz3'];
                $temp [22] = $apply_state_arr [$val ['apply_state']] ?? '';
                $temp [23] = $v ['goods_info'] ['goods_name'];
                $temp [24] = $v ['goods_info'] ['jun_id'];
                $temp [25] = $v ['goods_num'];
                $temp [26] = $v ['goods_price'];
                $temp [27] = $v ['goods_num'] * $v ['goods_price'];
                $zhekou = round($v ['goods_price'] * $supplier_rate) / 100;
                $temp [28] = number_format($zhekou, 2, '.', '');
                $temp [29] = $v ['diy_gys'];
                $temp [30] = $v ['div_cgj'];
                $temp [31] = $v ['diy_fpzt'];
                $temp [32] = $v ['diy_fpdj'];
                array_push($excel_data, $temp);
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    public function downExcel($excel_name)
    {
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 23; $y++) {
                        $cell_value = chr($start + $y);
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 23; $y++) {
                $cell_value = chr($start + $y);
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    // 查询订单是否存在

    public function searchOrderNo()
    {
        $get_order_nos = explode('<br />', nl2br($this->post['order_nos']));
        $new_order = [];
        foreach ($get_order_nos as $key => $val) {
            array_push($new_order, trim($val));
        }
        $result = [];
        if (count($new_order) > 0) {
            $get_order_nos = $this->db
                ->whereIn('out_order_no', $new_order)
                ->select();
            for ($i = 0; $i < count($new_order); $i++) {
                $temp = [];
                $temp['out_order_no'] = $new_order[$i];
                $temp['flag'] = false;
                foreach ($get_order_nos as $key => $val) {
                    if ($new_order[$i] == $val['out_order_no']) {
                        $temp['flag'] = true;
                        $temp['order_info'] = $val;
                        $temp['order_no'] = $val['order_no'];
                    }
                }
                array_push($result, $temp);
            }
        }
        $this->layuiReturn($result);
    }

    public function detail()
    {
        if (isset ($this->post ['site_id'])) {
            $site_id = $this->post ['site_id'];
        } else {
            $site_id = SITE_ID;
        }

        $this->assign('site_id', $site_id);
        $this->db->param ['need_pay_info'] = 'yes';
        $this->db->param ['rate_price'] = 'yes';
        $this->db->param ['need_cart'] = 'yes';
        $return = $this->db->ajaxFind();
        $temp_s = json_decode($return ['api_param'], true);
        $this->assign('jun_param', $temp_s);
        if (!$return) {
            exit ('订单错误');
        }
        // 优士发票信息
        $siteConfigdb = new SiteConfigdb ();
        $siteConfigdb->param ['config_name'] = 'INVOICE_INFO';
        $get_config_value = $siteConfigdb->getValue();
        $this->assign('invoice_info', str_replace(chr(10), '<br />', $get_config_value));
        // 发票结束
        $return ['invoice_info_list'] = $return ['invoice_info'];
        if (count($return ['invoice_info']) == 1 && (SITE_ID == 10 || SITE_ID == 13)) {
            $return ['invoice_info'] = $return ['invoice_info'] [0];
            $return ['invoice_info_json'] = json_encode($return ['invoice_info']);
        }
        $memberdb = new Memberdb ();
        $supplier_field = 'member_id,supplier_rate,supplier_name';
        $get_supplier = $memberdb->where('is_supplier', 1)->field($supplier_field)->order('member_id desc')->select();
        if ($get_supplier) {
            $get_supplier = $get_supplier->toArray();
        } else {
            $get_supplier = [];
        }
        $return['api_param_arr'] = json_decode($return['api_param'], true);
        $this->assign('get_supplier', $get_supplier);
        $this->assign('get_supplier_json', json_encode($get_supplier));
        $this->assign('data', $return);
        switch ($return ['order_state']) {
            case '1' :
                $this->assign('goods_cols', json_encode($this->goods_cols));
                break;
            case '2' :
                $this->assign('goods_cols', json_encode($this->goods_cols_state2));
                break;
            case '3' :
            case '4' :
            case '5' :
                if ($return ['shopping_state'] == 2) {
                    unset ($this->goods_cols_state2 [0]);
                };
                $this->assign('goods_cols', json_encode($this->goods_cols_state2));
                // 查找安装服务产品
                $cartdb = new Cartdb ();
                $cartdb->param ['order_no'] = $return ['order_no'];
                $cartdb->param ['pack_state'] = 1;
                $cartdb->param ['is_install'] = 1;
                $cartdb->param ['need_goods_info'] = 'yes';
                $is_install = $cartdb->ajaxList();
                $this->assign('is_install', $is_install);
                break;
            default :
                $this->assign('goods_cols', json_encode($this->goods_cols_state2));
                break;
        }
        if ($return ['order_state'] > 2) {
            // 调用发货信息
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $return ['order_no'];
            $express_list = $expressdb->ajaxList();
            $this->assign('express_list', $express_list);
        }
        // 调用快递100返回的信息
        $postwuliuDb = new Postwuliudb();
        $get_wuliu = $postwuliuDb->where('order_id', $return['order_id'])->order('postwuliu_id', 'desc')->find();
        $kuaidi = [];
        $kuaidi['nu'] = '';
        $kuaidi['data'] = [];
        if ($get_wuliu) {
            $get_wuliu_param = json_decode($get_wuliu['post_json'], true);
            $get_wuliu_data = json_decode($get_wuliu_param['param'], true);
            $kuaidi = $get_wuliu_data['lastResult'];
        }

        // 验证推送物流信息是否完成
        $runsdb = new Runsdb();
        $chk_runs_over = $runsdb
            ->where('order_no', $return['order_no'])
            ->where('state', 2)
            ->count();
        $this->assign('chk_runs_over', $chk_runs_over);
        $this->assign('kuaidi', $kuaidi);
        $this->assign('select_goods_cols', json_encode($this->select_goods_cols));
        $this->assign('goods_cols_invoice', json_encode($this->goods_cols_invoice));

// 调用日志
        // 调用日志
        $orderLogdb = new OrderLogdb ();
        $orderLogdb->param ['order_no'] = $this->post ['order_no'];
        $orderLogdb->param ['type_index'] = 1000;
        $get_log = $orderLogdb->ajaxList();
        $this->assign('order_log', $get_log);
        // 客服提醒
        $orderRemarkdb = new OrderRemarkdb();
        $get_remark = $orderRemarkdb
            ->where('order_no', $this->post['order_no'])
            ->where('remark_type', 2)
            ->order('create_time', 'desc')->select();
        $this->assign('orderRemark', $get_remark);
        return $this->fetch();
    }

    public function getCartList()
    {
        $cartdb = new Cartdb();
        $get_cart = $cartdb->with(['goods'])->where('order_no', $this->post['order_no'])->select();
        foreach ($get_cart as $key => $val) {
            $get_cart[$key]['goods_name'] = $val['goods']['goods_name'] ?? '';
            $get_cart[$key]['all_sale_price'] = number_format($val['goods_sale_price'] * $val['goods_num'], 2, '.', '');
            $get_cart[$key]['goods_jun_id'] = $val['goods']['jun_id'] ?? '';
        }
        $this->layuiReturn($get_cart, count($get_cart));
    }

    public function saveSupplier()
    {
        $data ['supplier_id'] = $this->post ['supplier_id'];
        $data ['supplier_rate'] = $this->post ['supplier_rate'];
        $data ['supplier_state'] = 3;
        $this->db->save($data, [
            'order_no' => $this->post ['order_no']
        ]);
        $this->db->clearCache();
        $this->layuiReturn('保存成功');
    }

    public function confirmSupplier()
    {
        $data ['supplier_state'] = 1;
        $data ['huikuandanwei'] = $this->post ['huikuandanwei'];
        $data ['xsht'] = '生成中';
        $data ['cght'] = '生成中';
        $data ['shd'] = '生成中';
        $data ['xsfp'] = '生成中';
        $data ['cgfp'] = '生成中';
        //$data ['ysd'] = '生成中';
        $data['supplier_confirm_time'] = time();
        $this->db->save($data, [
            'order_no' => $this->post ['order_no']
        ]);
        $this->db->clearCache();
        $tpl [0] ['buildtpl_type'] = 'xsht';
        $tpl [0] ['order_no'] = $this->post ['order_no'];
        $tpl [1] ['buildtpl_type'] = 'cght';
        $tpl [1] ['order_no'] = $this->post ['order_no'];
        $tpl [2] ['buildtpl_type'] = 'shd';
        $tpl [2] ['order_no'] = $this->post ['order_no'];
        $tpl [3] ['buildtpl_type'] = 'xsfp';
        $tpl [3] ['order_no'] = $this->post ['order_no'];
        $tpl [4] ['buildtpl_type'] = 'cgfp';
        $tpl [4] ['order_no'] = $this->post ['order_no'];
        /*$tpl [5] ['buildtpl_type'] = 'ysd';
        $tpl [5] ['order_no'] = $this->post ['order_no'];*/
        $buildtpldb = new Buildtpldb();
        $buildtpldb->saveAll($tpl);
        // 日志流转
        $order_logdb = new OrderLogdb ();
        $order_logdb->param = array(
            'type_index' => 3,
            'order_no' => $this->post ['order_no'],
            'member_id' => MEMBER_ID,
            'view_text' => '已确认订单',
            'post_json' => $this->post
        );
        $order_logdb->saveData();
        $this->layuiReturn('保存成功');
    }


    /**
     * Title("导出采购发票明细")
     */
    public function excelGysInvoiceAll()
    {
        set_time_limit(0);
        ini_set('memory_limit', '4096M');
        $orderdb = new Orderdb();
        $orderdb->param = $this->post;
        $orderdb->param ['supplier_id'] = MEMBER_ID;
        $get_order = $orderdb->order('order_id desc')->select();
        if (!$get_order->isEmpty()) {
            $cartdb = new Cartdb ();
            $memberdb = new Memberdb ();
            $goodsdb = new Goodsdb ();
            $shoppingdb = new Shoppingdb ();
            $get_order = $get_order->toArray();
            $new_order = array();
            foreach ($get_order as $key => $val) {
                $temp_api = json_decode($val['api_param'], true);
                $get_order[$key]['beizhu'] = isset($temp_api['remark']) ? $temp_api['remark'] : '';
                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'] / 100;
                if ($val ['supplier_id']) {
                    $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $val ['supplier_id'])->find()->toArray();
                    $get_order [$key] ['supplier_name'] = $get_supplier ['supplier_name'];
                    $get_order [$key] ['yewuyuan'] = $get_supplier ['yewuyuan'];
                } else {
                    $get_order [$key] ['supplier_name'] = '未指定供应商';
                    $get_order [$key] ['yewuyuan'] = '';
                }
                $get_cart = $cartdb->useGlobalScope(false)->where('order_no', $val ['order_no'])->select();
                if (!$get_cart->isEmpty()) {
                    $get_cart = $get_cart->toArray();
                    $zhekou_money = 0;
                    foreach ($get_cart as $k => $v) {
                        $zhekou_money += number_format(round($v ['goods_price'] * $val ['supplier_rate']) * $v ['goods_num'] / 100, 2, '.', '');
                        $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $v ['goods_sku'])->where('site_id', SITE_ID)->find();
                        if ($get_goods) {
                            $get_cart [$k] ['goods_info'] = $get_goods->toArray();
                        }
                    }
                    $get_order [$key] ['supplier_rate_money'] = $zhekou_money;
                    $get_order [$key] ['cart_info'] = $get_cart;
                }
                $shop_info = array(
                    'contacts' => '无',
                    'phone' => '无'
                );
                if ($val ['shopping_id']) {
                    $get_shopping = $shoppingdb->useGlobalScope(false)->where('shopping_id', $val ['shopping_id'])->find();
                    if ($get_shopping) {
                        $shop_info = $get_shopping->toArray();
                    }
                }
                $get_order [$key] ['shopping_info'] = $shop_info;
                $temp = json_decode($val ['api_param'], true);
                $get_order [$key] ['citys'] = $temp ['Cityname'] . $temp ['address'];
                if ((isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') || (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes')) {
                    // 如果导出的是更换供货商 这里这不推送数据
                } else {
                    array_push($new_order, $get_order [$key]);
                }
                if (isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') {
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);
                        if ($temp_s > 1) {
                            for ($x = 0; $x < count($temp_s) - 1; $x++) {
                                $get_order [$key] ['order_state'] = -2;
                                $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                                $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                                $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                            }
                        }
                    }
                }
                if (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes') {
                    $supplier_name = '';
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);

                        if (count($temp_s) > 0) {
                            $supplier_name = $temp_s [count($temp_s) - 1] ['supplier_name'];
                        }
                    }
                    $get_order [$key] ['order_state'] = -2;
                    $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                    $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                    $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                    $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                }
            }
        }
        $data = $new_order;
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '采购发票' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '订单号',
            '订单类型',
            '单位名称',
            '纳税识别号',
            '地址、电话',
            '开户行及账号',
            '供应商',
            '税务大类',
            '税务编码',
            '商品名称',
            '开票名称',
            '规格型号',
            '数量',
            '单位',
            '采购单价（元）',
            '采购金额（元）',
            '税率',
        );
        $this->setExcelHeader2($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        foreach ($data as $key => $val) {
            $cg_money = 0;
            if (!isset($val ['cart_info'])) {
                continue;
            }
            foreach ($val ['cart_info'] as $k => $v) {
                if (isset($v ['goods_info']) && $v['goods_info']) {
                    unset ($temp);
                    $pay_type = $val ['pay_type'] ? $val ['pay_type'] : 1;
                    $supplier_rate = $val ['supplier_rate'] ? $val ['supplier_rate'] : 100;
                    $temp [0] = $val ['out_order_no'] . " ";
                    $temp [1] = $order_type_arr [$val ['order_type']];
                    $temp [2] = '北京市泰龙吉贸易有限公司';
                    $temp [3] = '91110105675715354X';
                    $temp [4] = '北京市朝阳区管庄乡杨闸村京通辅路南8号院 F1 010-59521909';
                    $temp [5] = '交通银行北京林萃路支行  110061203018010014524';
                    $temp [6] = $val ['supplier_name'];
                    $temp [7] = $v['product_area'] ?: $v['goods_info']['product_area'];
                    $temp [8] = "\t".($v['shuiwu_id'] ?: $v['goods_info']['shuiwu_id']);
                    $temp [9] = $v ['goods_info'] ['goods_name'];
                    $temp [10] = $v['product_firm'] ?: $v['goods_info']['product_firm'];
                    $temp [11] = $v['invoice_model'] ?: $v['goods_info']['invoice_model'];
                    $temp [12] = $v ['goods_num'];
                    $temp [13] = $v['goods_unit'] ?: $v['goods_info']['goods_unit'];
                    $zhekou = round($v ['goods_price'] * $supplier_rate) / 100;
                    $temp [14] = number_format($zhekou, 2, '.', '');
                    $temp [15] = number_format($temp [14] * $v ['goods_num'], 2, '.', '');
                    $cg_money += $temp [15];
                    $temp [16] = $v['goods_keywords'] ?: $v['goods_info']['goods_keywords'];
                    array_push($excel_data, $temp);
                }
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody2($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel2', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    public function downExcel2($excel_name)
    {
        $excel_name = str_replace('.html', '', $excel_name);
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    protected function setExcelHeader2($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody2($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 7; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 7; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    // 手动生成验收单
    public function exportyanshoudan()
    {
        $data ['ysd'] = '生成中';
        $this->db->save($data, [
            'order_no' => $this->post ['order_no']
        ]);
        $this->db->clearCache();
        $tpl ['buildtpl_type'] = 'ysd';
        $tpl ['order_no'] = $this->post ['order_no'];
        $buildtpldb = new Buildtpldb();
        $buildtpldb->save($tpl);
        $this->layuiReturn('保存成功');
    }

    public function saveData()
    {
        $return = $this->db->addOrder();
        if ($return != 'success') {
            $this->layuiReturn($return, 0, $return, -1);
        } else {
            $this->layuiReturn('保存成功');
        }
    }

    public function editOrder()
    {
        $return = $this->db->editOrder();
        if ($return == 'success') {
            $this->layuiReturn('保存成功');
        } else {
            $this->layuiReturn($return, 0, $return, -1);
        }
    }

    /**
     * Title("修改订单备注3信息")
     */
    public function cartBeizhu()
    {
        $cartdb = new Cartdb();
        $get_cart = $cartdb->where('order_no', $this->post['order_no'])->where('goods_sku', $this->post['goods_sku'])->find();
        if ($get_cart) {
            $get_cart->save(['goods_beizhu3' => $this->post['value']]);
            // 写日志
            $remark_log = [];
            $remark_log['order_no'] = $this->post['order_no'];
            $remark_log['goods_sku'] = $this->post['goods_sku'];
            $remark_log['goods_name'] = Db::name('goods')->where('goods_sku', $this->post['goods_sku'])->value('goods_name');
            $remark_log['member_id'] = MEMBER_ID;
            $remark_log['username'] = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
            $remark_log['value'] = $this->post['value'];
            $remark_log['date'] = date('Y-m-d H:i:s');
            $remarkLogdb = new OrderGoodsRemarkdb();
            $remarkLogdb->save($remark_log);
            // 日志结束
            // 同步分系统
            $ucartdb = new UCartdb();
            $get_u_cart = $ucartdb->where('order_no', $this->post['order_no'])->where('goods_sku', $this->post['goods_sku'])->find();
            if ($get_u_cart) {
                $get_u_cart->save(['goods_beizhu3' => $this->post['value']]);
                // 同步日志
                $jremarkLogdb = new UOrderGoodsRemarkdb();
                $jremarkLogdb->save($remark_log);
            }
        }
        $this->layuiReturn('保存成功');
    }
    /**
     * Title("获取订单商品备注修改日志")
     */
    public function orderGoodsRemarkLog()
    {
        $data = Db::name('order_goods_remark')->where('order_no', $this->post['order_no'])->order('id desc')->select();
        $this->layuiReturn($data);
    }

    public function addExpress()
    {
        $return = $this->db->addExpress();
        if ($return == 'success') {
            $this->layuiReturn('保存成功');
        } else {
            $this->layuiReturn($return, 1, $return, 1);
        }
    }

    public function tplForm()
    {
        $this->assign('member_cols', json_encode($this->member_cols));
        $this->assign('goods_cols', json_encode($this->goods_cols));
        $this->assign('select_goods_cols', json_encode($this->select_goods_cols));
        return $this->fetch();
    }

    public function addInstallInfo()
    {
        $installdb = new Installdb ();
        $installdb->param = $this->post;
        $installdb->addInstallInfo();
        $this->layuiReturn('保存成功');
    }

    // 支付信息
    public function addPayInfo()
    {
        $this->db->param = array();
        $this->db->param ['event'] = 'add_pay';
        $this->db->param ['order_no'] = $this->post ['order_no'];
        $cartdb = new Cartdb ();
        $cartdb->param ['order_no'] = $this->post ['order_no'];
        $this->db->param ['cart_ids'] = $cartdb->ajaxCartIds();
        unset ($this->post ['order_no']);
        $this->post ['pay_state'] = 2;
        $this->post ['pay_time'] = time();
        $this->db->param ['post_data'] = $this->post;
        $this->db->editOrder();
        $this->layuiReturn('支付成功');
    }

    public function returned()
    {
        $returneddb = new Returneddb ();
        $returneddb->param = $this->post;
        $returneddb->ajaxSave();
        // 处理cart
        $cartdb = new Cartdb ();
        $cartdb->param ['order_no'] = $this->post ['order_no'];
        $cartdb->param ['goods_sku'] = $this->post ['goods_sku'];
        if ($this->post ['returned_type'] == 1) {
            // 退货
            $cartdb->param ['returned_state'] = 2;
        } else {
            $cartdb->param ['returned_state'] = 4;
        }
        $cartdb->setReturned();
        $this->layuiReturn('保存成功');
    }

    public function getShoppingPhone()
    {
        $shoppingdb = new Shoppingdb();
        $get_shopping = $shoppingdb->where('phone', $this->post['phone'])->column('shopping_id');
        $orderdb = new Orderdb();
        $get_order = $orderdb->whereIn('shopping_id', $get_shopping)->group('huikuandanwei')->column('huikuandanwei');
        $this->layuiReturn($get_order);
    }

    /**
     *
     * @todo 软删除
     */
    public function ajaxDelete()
    {
        $this->db->param = $this->post;
        $this->db->ajaxDelete();
        $this->layuiReturn('删除成功', 0);
    }

    // 采购合同
    public function caigouht($order_no)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find()->toArray();
        $cart_arr = array();
        $cartdb = new Cartdb ();
        $cart_arr = $cartdb->where('order_no', $get_order ['order_no'])->order('cart_id asc')->select()->toArray();
        $goodsdb = new Goodsdb ();
        foreach ($cart_arr as $key => $val) {
            $cart_arr [$key] ['goods_info'] = $goodsdb->where('goods_sku', $val ['goods_sku'])->where('site_id', $val ['site_id'])->find()->toArray();
        }
        $get_order ['cart_info'] = $cart_arr;
        if ($get_order['supplier_id']) {
            $memberdb = new Memberdb ();
            $get_supplier = $memberdb->where('member_id', $get_order['supplier_id'])->find();
            if ($get_supplier) {
                $get_supplier = $get_supplier->toArray();
                $get_order ['supplier_name'] = $get_supplier ['supplier_name'];
            } else {
                $get_order ['supplier_name'] = '';
            }
        }
        $this->assign('order_info', $get_order);
        $this->assign('get_supplier', $get_supplier);
        return $this->fetch();
    }

    /*
     * 导出采购合同
     */
    public function exportCaigouht($order_no)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $pdf = new \TCPDF ('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        $html = file_get_contents('http://' . $_SERVER ['HTTP_HOST'] . url('order/caigouht', array(
                'order_no' => $order_no,
                'member_id' => MEMBER_ID
            )));
        $pdf->AddPage();
        $pdf->writeHTML($html);
        $pdf->Output('采购' . date('YmdHi') . '.pdf', 'D');
        exit ('完成');
    }

    // 销售合同
    public function saleht($order_no)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find()->toArray();
        $cart_arr = array();
        $cartdb = new Cartdb ();
        $cart_arr = $cartdb->where('order_no', $get_order ['order_no'])->order('cart_id asc')->select()->toArray();
        $goodsdb = new Goodsdb ();
        $branddb = new Branddb ();
        foreach ($cart_arr as $key => $val) {
            $cart_arr [$key] ['goods_info'] = $goodsdb->where('goods_sku', $val ['goods_sku'])->where('site_id', $val ['site_id'])->find()->toArray();
            $get_brand = $branddb->where('brand_sign', $cart_arr [$key] ['goods_info'] ['brand_sign'])->find()->toArray();
            $cart_arr [$key] ['goods_info'] ['brand_name'] = $get_brand ['brand_name'];
        }
        $get_order ['cart_info'] = $cart_arr;
        $this->assign('order_info', $get_order);
        dump($get_order);
        return $this->fetch();
    }

    /*
     * 导出销售合同
     */
    public function exportSaleht($order_no)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $pdf = new \TCPDF (PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        $html = file_get_contents('http://' . $_SERVER ['HTTP_HOST'] . url('order/saleht', array(
                'order_no' => $order_no,
                'member_id' => MEMBER_ID
            )));
        $pdf->AddPage();
        $pdf->writeHTML($html);
        $img = 'https://tailongji.dixintong.com/zhang.png';
        $all_page = $pdf->getNumPages();
        for ($i = 0; $i < $all_page; $i++) {
            $pdf->setPage($i + 1);
            $pdf->Image($img, 195, 60, 40, 40, 'png', '', '');
        }
        $pdf->Output('销售' . date('YmdHi') . '.pdf', 'D');
        exit ('完成');
    }

    public function songhuodan($order_id)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_id', $order_id)->find()->toArray();
        switch ($get_order) {
            case '1' :
                $get_order ['pay_type_text'] = '货到付款';
                break;
            case '2' :
                $get_order ['pay_type_text'] = '在线支付';
                break;
            case '3' :
                $get_order ['pay_type_text'] = '账期支付';
                break;
            case '4' :
                $get_order ['pay_type_text'] = '银行转账';
                break;
            default :
                $get_order ['pay_type_text'] = '货到付款';
                break;
        }
        $get_order ['api_param_json'] = json_decode($get_order ['api_param'], true);
        $get_order['supplier_info'] = array();
        $supplier_info = Memberdb::where('member_id', $get_order['supplier_id'])->find();
        if ($supplier_info) {
            $get_order['supplier_info'] = $supplier_info->toArray();
        }
        $cart_arr = array();
        $cartdb = new Cartdb ();
        $cart_arr = $cartdb->where('order_no', $get_order ['order_no'])->order('cart_id asc')->select()->toArray();
        $goodsdb = new Goodsdb ();
        foreach ($cart_arr as $key => $val) {
            $cart_arr [$key] ['goods_info'] = $goodsdb->where('goods_sku', $val ['goods_sku'])->where('site_id', $val ['site_id'])->find()->toArray();
        }
        $get_order ['cart_info'] = $cart_arr;
        $this->assign('order_info', $get_order);
        return $this->fetch();
    }

    /*
     * 导出送货单
     */
    public function exportSonghuodan($order_ids)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $temp = explode(',', $order_ids);
        $html = '';
        $pdf = new \TCPDF (PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        foreach ($temp as $key => $val) {
            $html = file_get_contents('http://' . $_SERVER ['HTTP_HOST'] . url('order/songhuodan', array(
                    'order_id' => $val,
                    'member_id' => MEMBER_ID
                )));
            $pdf->AddPage();
            $pdf->writeHTML($html);
        }
        $pdf->Output('送货单' . date('YmdHi') . '.pdf', 'D');
        exit ('完成');
    }

    public function yanshoudan($order_id)
    {
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_id', $order_id)->find()->toArray();
        switch ($get_order) {
            case '1' :
                $get_order ['pay_type_text'] = '货到付款';
                break;
            case '2' :
                $get_order ['pay_type_text'] = '在线支付';
                break;
            case '3' :
                $get_order ['pay_type_text'] = '账期支付';
                break;
            case '4' :
                $get_order ['pay_type_text'] = '银行转账';
                break;
            default :
                $get_order ['pay_type_text'] = '货到付款';
                break;
        }
        $get_order ['api_param_json'] = json_decode($get_order ['api_param'], true);
        $get_order['supplier_info'] = array();
        $supplier_info = Memberdb::where('member_id', $get_order['supplier_id'])->find();
        if ($supplier_info) {
            $get_order['supplier_info'] = $supplier_info->toArray();
        }
        $cart_arr = array();
        $cartdb = new Cartdb ();
        $cart_arr = $cartdb->where('order_no', $get_order ['order_no'])->order('cart_id asc')->select()->toArray();
        $goodsdb = new Goodsdb ();
        foreach ($cart_arr as $key => $val) {
            $cart_arr [$key] ['goods_info'] = $goodsdb->where('goods_sku', $val ['goods_sku'])->where('site_id', $val ['site_id'])->find()->toArray();
        }
        $get_order ['cart_info'] = $cart_arr;
        $this->assign('order_info', $get_order);
        return $this->fetch();
    }

    /*
     * 导出送货单
     */
    public function exportYanshoudan_back($order_ids)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $temp = explode(',', $order_ids);
        $html = '';
        $pdf = new \TCPDF (PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        foreach ($temp as $key => $val) {
            $html = file_get_contents('http://' . $_SERVER ['HTTP_HOST'] . url('order/yanshoudan', array(
                    'order_id' => $val,
                    'member_id' => MEMBER_ID
                )));
            $pdf->AddPage();
            $pdf->writeHTML($html);
        }
        $pdf->Output('验收单' . date('YmdHi') . '.pdf', 'D');
        exit ('完成');
    }
    /**
     * Title("发送邮件附件")
     */
    public function sendMailAttr()
    {
        $order_db = new Orderdb();
        $get_order = $order_db->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            // 添加zip
            $zip_name = 'uploads/Excel/zip/' . $get_order['out_order_no'] . '打包信息' . date('Ymdhi') . '.' . rand(1000, 9999) . '.zip';
            $attr_name = $get_order['out_order_no'] . '打包信息.zip';
            $zip = new \ZipArchive();
            $zip->open($zip_name, \ZipArchive::CREATE);
            if ($zip == true) {
                $base_url = '/www/wwwroot/dxtadmin/';
                // 添加销售合同
                $xs_file = 'uploads/Excel/sale/' . $get_order['out_order_no'] . '销售合同.pdf';
                if (file_exists($base_url . $xs_file)) {
                    $zip->addFile($base_url . $xs_file, '销售合同.pdf');
                }
                // 添加送货单
                $shd_file = 'uploads/Excel/hetong/' . $get_order['out_order_no'] . '送货验收单.pdf';
                if (file_exists($base_url . $shd_file)) {
                    $zip->addFile($base_url . $shd_file, '送货单.pdf');
                }
                // 添加验收单
                $ysd_file = 'uploads/Excel/hetong/' . $get_order['out_order_no'] . '验收单.pdf';
                if (file_exists($base_url . $ysd_file)) {
                    $zip->addFile($base_url . $ysd_file, '验收单.pdf');
                }
                // 添加发票
                $get_invoice = Db::name('upload')->where('upload_id', Db::name('invoice')->where('order_nos', $get_order['order_no'])->value('invoice_proof'))->find();
                if ($get_invoice) {
                    $fp_file = str_replace('./', 'uploads/', $get_invoice['save_path']);
                    $fp_file = str_replace('https://tailongji.dixintong.com/','',$fp_file);
                    $fp_file = str_replace('http://tailongji.dixintong.com/','',$fp_file);
                    $fp_file = str_replace('https://fen.utecbj.com/','',$fp_file);
                    $fp_file = str_replace('http://fen.utecbj.com/','',$fp_file);
                    if (file_exists($base_url . $fp_file)) {
                        $zip->addFile($base_url . $fp_file, '发票.pdf');
                    }
                }
                // 添加采购发票
                if (stripos($get_order['cgfp'], 'http') === 0) {
                    $fp_file = str_replace('./', 'uploads/', $get_order['cgfp']);
                    $fp_file = str_replace('https://tailongji.dixintong.com/', '', $fp_file);
                    $fp_file = str_replace('http://tailongji.dixintong.com/', '', $fp_file);
                    $fp_file = str_replace('https://fen.utecbj.com/', '', $fp_file);
                    $fp_file = str_replace('http://fen.utecbj.com/', '', $fp_file);
                    if (file_exists($base_url . $fp_file)) {
                        $zip->addFile($base_url . $fp_file, '采购发票.xls');
                    }
                }
            }
            $zip->close();
            $result = $this->sendMailTpl($this->post['to_mail'], $_SERVER['DOCUMENT_ROOT'].'/' . $zip_name, $get_order['out_order_no'] . '打包信息--泰龙吉', $attr_name);
            if ($result == true) {
                // 修改订单状态
                $params = json_decode($get_order['api_param'], true);
                $save_order = [];
                $save_order['is_send_mail'] = 1;
                if ($params['email'] != $this->post['to_mail']) {
                    $params ['email'] = $this->post['to_mail'];
                    $save_order['api_param'] = json_encode($params);
                }
                $get_order->save($save_order);
                // 同步分系统
                $jorderdb = new UOrderdb();
                $get_j_order = $jorderdb->where('order_no', $get_order['order_no'])->find();
                if ($get_j_order) {
                    $get_j_order->save($save_order);
                }
                $this->layuiReturn('', 1, '发送成功', 1);
            } else {
                $this->layuiReturn('', 1, '邮件发送失败', 2);
            }
        } else {
            $this->layuiReturn('', 1, '订单失败', 2);
        }

    }
    /**
     * Title("获取快递公司列表")
     */
    public function KuaidiList()
    {
        $get_com = Db::name('kuaidi')->order('kuaidi_id asc')->column('kuaidiname');
        $this->layuiReturn($get_com, count($get_com), 'success', 1);
    }

    /**
     * Title("上传采购合同1")
     */
    public function saveCght1(){
        $get_order = $this->db->where('order_no',$this->post['order_no'])->find();
        if($get_order){
            $get_order->save(['cght1'=>$this->post['caigou_hetong']]);
        }
        $this->layuiReturn('success', 0, 'success', 1);
    }
}